<?php
class ome_mdl_goods extends dbeav_model{
   var $defaultOrder = array('d_order',' DESC',',p_order',' DESC',',goods_id',' DESC');
    var $has_many = array(
        'product' => 'products:contrast',
        //'keywords'=>'goods_keywords:replace',
        //'images' => 'image_attach@image:contrast:target_id',
        'tag'=>'tag_rel@desktop:replace:goods_id^rel_id',
    );
    var $has_one = array(

    );
    var $flag = false;
    var $subSdf = array(
            'default' => array(

                'keywords'=>array('*'),
                'product'=>array(
                    '*'
                    ,
//                    array(
//                        'price/ome_lv_price'=>array('*')
//                    )
                ),
                ':goods_type'=>array(
                    '*'
                ),
                'tag'=>array(
                    '*',array(
                        ':tag'=>array('*')
                    )
                ),
            )
        );

    function __construct($app){
        parent::__construct($app);
        //member中的扩展属性将通过meta系统进行存储
        $this->use_meta();
    }
    var $ioSchema = array(
        'csv' => array(
            'bn:商品编号' => 'bn',
            'barcode:条形码' => 'barcode',
            'ibn:货号' => array('bn','product'),
            //'col:分类' => 'category/cat_id',
            'col:品牌' => 'brand/brand_id',
            //'col:市场价' => array('price/mktprice/price','product'),
            //'col:成本价' => array('price/cost/price','product'),
            //'col:销售价' => array('price/price/price','product'),
            'col:商品名称' => 'name',
            //'col:上架' => 'status',
            'col:规格' => 'spec',
            //'col:商品简介' => 'brief',
            //'col:详细介绍' => 'description',
            'col:重量' => 'weight',
            'col:单位' => 'unit',
        ),
    );

    function checkProductBn($bn, $gid=0){
        $bn = addslashes($bn);
        if($bn == ''){
            return false;
        }
        if($gid){
            $sql = 'SELECT count(*) AS num FROM sdb_ome_products WHERE bn = \''.$bn.'\' AND goods_id != '.$gid;
            $Gsql = 'SELECT count(*) AS num FROM sdb_ome_goods WHERE bn = \''.$bn.'\' AND goods_id != '.$gid;
        }else{
            $sql = 'SELECT count(*) AS num FROM sdb_ome_products WHERE bn = \''.$bn.'\'';
            $Gsql = 'SELECT count(*) AS num FROM sdb_ome_goods WHERE bn = \''.$bn.'\'';
        }
        $aTmp = $this->db->selectrow($sql);
        $GaTmp = $this->db->selectrow($Gsql);
        return $aTmp['num']+$GaTmp['num'];
    }
    
    /**
     * 检测条形码，不允许重复
     */
    function checkBarcode($barcode, $gid=0){
        $barcode = addslashes($barcode);
        if($barcode == ''){
            return false;
        }
        if($gid){
            $sql = 'SELECT count(*) AS num FROM sdb_ome_products WHERE barcode = \''.$barcode.'\' AND goods_id != '.$gid;
            $Gsql = 'SELECT count(*) AS num FROM sdb_ome_goods WHERE barcode = \''.$barcode.'\' AND goods_id != '.$gid;
        }else{
            $sql = 'SELECT count(*) AS num FROM sdb_ome_products WHERE barcode = \''.$barcode.'\'';
            $Gsql = 'SELECT count(*) AS num FROM sdb_ome_goods WHERE barcode = \''.$barcode.'\'';
        }
        $aTmp = $this->db->selectrow($sql);
        $GaTmp = $this->db->selectrow($Gsql);
        return $aTmp['num']+$GaTmp['num'];
    }

     function io_title( $filter,$ioType='csv' ){
        $title = array();
        switch( $ioType ){
            case 'csv':
            default:
                $oGtype = $this->app->model('goods_type');
                if( $this->csvExportGtype[$filter['type_id']] )
                    $gType = $this->csvExportGtype[$filter['type_id']];
                else
                    $gType = $oGtype->dump($filter['type_id'],'*');
                $title = array(
                    '*:'.$gType['name'],
                    'bn:商品编号',
                    'barcode:条形码',
                    'ibn:货号',
                    //'col:分类',
                    'col:品牌',
                    //'col:市场价',
                    //'col:成本价',
                    //'col:销售价',
                    'col:商品名称',
                      //'col:上架',
                      'col:规格',
                );
                $this->oSchema['csv'][$filter['type_id']] = array(
                    '*:'.$gType['name']=>'type/name',
                    'bn:商品编号' => 'bn',
                    'barcode:条形码'=>'barcode',
                    'ibn:货号' => array('bn','product'),
                    //'col:分类' => 'category/cat_name',
                    'col:品牌' => 'brand/brand_name',
                    //'col:市场价' => array('price/mktprice/price','product'),
                    //'col:成本价' => array('price/cost/price','product'),
                    //'col:销售价' => array('price/price/price','product'),
                    'col:商品名称' => 'name',
                    //'col:上架' => 'status',
                    'col:规格' => 'spec',
                );
//               // $oMlv = $this->app->model('ome_lv');
//                foreach( $oMlv->getList() as $mlv ){
//                    $title[] = 'price:'.$mlv['name'];
////                    $this->oSchema['csv'][$filter['type_id']]['price:'.$mlv['name']] = 'price/';
//                }
                $title = array_merge($title,array(
                    //'col:商品简介',
                    //'col:详细介绍',
                    'col:重量',
                    'col:单位',
                ));
                $this->oSchema['csv'][$filter['type_id']] = array_merge(
                    $this->oSchema['csv'][$filter['type_id']],
                    array(
                        //'col:商品简介' => 'brief',
                        //'col:详细介绍' => 'description',
                        'col:重量' => 'weight',
                        'col:单位' => 'unit',
                    )
                );
                if ($gType['props'])
                foreach( (array)$gType['props'] as $propsK => $props ){
                    $title[] = 'props:'.$props['name'];
                    $this->oSchema['csv'][$filter['type_id']]['props:'.$props['name']] = 'props/p_'.$propsK;
                }
                break;
        }
        $this->ioTitle['csv'][$filter['type_id']] = $title;
        return $title;
    }

    function dump($filter,$field = '*',$subSdf = null){
        $dumpData = &parent::dump($filter,$field,$subSdf);
        $oSpec = &$this->app->model('specification');
        if( $dumpData['spec_desc'] ){
            foreach( $dumpData['spec_desc'] as $specId => $spec ){
                $dumpData['spec'][$specId] = $oSpec->dump($specId,'*');
                if ($spec)
                foreach( $spec as $pSpecId => $specValue ){
                    $dumpData['spec'][$specId]['option'][$pSpecId] = array_merge( array('private_spec_value_id'=>$pSpecId), $specValue );
                }
            }
        }
        unset($dumpData['spec_desc']);
        return $dumpData;
    }

/*function getList($cols='*',$filter=array(),$start=0,$limit=-1,$orderType=null){
        if (kernel::servicelist('ome_goods_list_apps'))
        foreach(kernel::servicelist('ome_goods_list_apps') as $object){
            return $object->goods_list($cols,$filter,$start,$limit,$orderType, $this);
        }
    }*/
    function _filter($filter,$tbase=''){
        foreach(kernel::servicelist('ome_goods_filter_apps') as $object){
            if(method_exists($object,'goods_filter')){
                $data = $object->goods_filter($filter, $this);
            }
            return $data;
        }
    }

    function wFilter($words){
        $replace = array(",","+");
        $enStr=preg_replace("/[^chr(128)-chr(256)]+/is"," ",$words);
        $otherStr=preg_replace("/[chr(128)-chr(256)]+/is"," ",$words);
        $words=$enStr.' '.$otherStr;
        $return=str_replace($replace,' ',$words);
        $word=preg_split('/\s+/s',trim($return));
        $GLOBALS['search_array']=$word;
        foreach($word as $k=>$v){
            if($v){
                $goodsId = array();
                foreach($this->getGoodsIdByKeyword(array($v)) as $idv)
                    $goodsId[] = $idv['goods_id'];
                foreach( $this->db->select('SELECT goods_id FROM sdb_ome_products WHERE bn = \''.trim($v).'\' ') as $pidv)
                    $goodsId[] = $pidv['goods_id'];
                $sql[]='(name LIKE \'%'.$word[$k].'%\' or bn like \''.$word[$k].'%\' '.( $goodsId?' or goods_id IN ('.implode(',',$goodsId).') ':'' ).')';
            }
        }
        return implode('and',$sql);
    }
    function getGoodsIdByKeyword($keywords , $searchType = 'tequal'){
        $where = '';
        switch( $searchType ){
            case 'has':
                $where = ' keyword LIKE "%'.implode( '%" AND keyword LIKE "%' ,$keywords ).'%" ';
                //like
                break;
            case 'nohas':
                $where = ' keyword NOT LIKE "%'.implode( '%" AND keyword NOT LIKE "%' ,$keywords ).'%" ';
                // not like
                break;
            case 'tequal':
            default:
                $where = ' keyword in ( "'.implode('","',$keywords).'" ) ';
                break;
        }
        return $this->db->select('SELECT goods_id FROM sdb_om_goods_keywords WHERE '.$where);
    }
    function save(&$goods,$mustUpdate = null){

        if( !$goods['bn'] ) $goods['bn'] = strtoupper(uniqid('g'));

        if( array_key_exists( 'spec',$goods ) ){
            if( $goods['spec'] )
                foreach( $goods['spec'] as $gSpecId => $gSpecOption ){
                    $goods['spec_desc'][$gSpecId] = $gSpecOption['option'];
                }
        } else{
                $goods['spec_desc'] = null;
        }
        $goodsStatus = false;
        if(is_array($goods['product'])){
            foreach( $goods['product'] as $pk => $pv ){
                if( $pv['bn'] == '' ) $goods['product'][$pk]['bn'] = strtoupper(uniqid('p'));
                if( !$pv['uptime'] ) $goods['product'][$pk]['uptime'] = time();
                $goods['product'][$pk]['name'] = $goods['name'];
                if (!$goods['product'][$pk]['barcode'])
                $goods['product'][$pk]['barcode'] = $goods['barcode'];
                if( $pv['status'] != 'false' ) $goodsStatus = true;
            }
        }
        if( !$goodsStatus )
            $goods['status'] = 'false';
        unset($goods['spec']);

      return parent::save($goods,$mustUpdate);
    }
    
    function unfreez($goods_id, $product_id, $num){
        $oPro = &$this->app->model('products');
        $sdf_pdt = $oPro->dump($product_id, 'freez');
        if($sdf_pdt['freez'] === null || $sdf_pdt['freez'] === ''){
            $sdf_pdt['freez'] = 0;
        }elseif($num < $sdf_pdt['freez']){
            $sdf_pdt['freez'] -= $num;
        }elseif($num >= $sdf_pdt['freez']){
            $sdf_pdt['freez'] = 0;
        }
        $sdf_pdt['product_id'] = $product_id;
        $sdf_pdt['last_modify'] = false;
        $oPro->save($sdf_pdt);
        return true;
    }

    function getFilterByTypeId($p){
        if(!function_exists('goods_filter_of_type')) require(CORE_DIR.'/lib/core/goods.filter_of_type.php');
        return goods_filter_of_type($p , $this);
    }

    function getFilter($p){
        if(!function_exists('goods_get_filter')) require(CORE_DIR.'/lib/core/goods.get_filter.php');
        return goods_get_filter($p , $this);
    }

    function orderBy($id=null){
        $order=array(
            array('label'=>app::get('base')->_('默认'),'sql'=>implode($this->defaultOrder,'')),
            array('label'=>app::get('base')->_('按发布时间 新->旧'),'sql'=>'last_modify desc'),
            array('label'=>app::get('base')->_('按发布时间 旧->新'),'sql'=>'last_modify'),
            array('label'=>app::get('base')->_('按价格 从高到低'),'sql'=>'price desc'),
            array('label'=>app::get('base')->_('按价格 从低到高'),'sql'=>'price'),
            array('label'=>app::get('base')->_('访问周次数'),'sql'=>'view_w_count desc'),
            array('label'=>app::get('base')->_('总访问次数'),'sql'=>'view_count desc'),
            array('label'=>app::get('base')->_('周购买次数'),'sql'=>'buy_count desc'),
            array('label'=>app::get('base')->_('总购买次数'),'sql'=>'buy_w_count desc'),
            array('label'=>app::get('base')->_('评论次数'),'sql'=>'comments_count desc'),
        );
        if($id){
            return $order[$id];
        }else{
            return $order;
        }
    }

    function prepared_import_csv_row($row,$title,&$goodsTmpl,&$mark,&$newObjFlag,&$msg){
        if (empty($row)){
            if(isset($this->same_bn)){
                if(count($this->same_bn) > 10){
                    for($i=0;$i<10;$i++){
                        $temp[] = current($this->same_bn);
                        next($this->same_bn);
                    }
                    $more = "...";
                }else{
                    $more = "";
                }
                $error_msg[] = "文件中以下商品编号重复：".implode(",",$this->same_bn).$more;
            }
            if(!empty($error_msg)){
                unset($this->bn_data);
                $msg['error'] = implode("     ",$error_msg);
                return false;
            }
        }
        if( substr($row[0],0,1) == '*' ){
            $mark = 'title';
            $newObjFlag = true;

            $oGType = &$this->app->model('goods_type');
            $goodsTmpl['gtype'] = $oGType->dump(array('name'=>ltrim($row[0],'*:')),'*','default');
            if( !$goodsTmpl['gtype'] ){
                $msg = array('error'=>'商品类型:'.ltrim( $row[0],'*:' ).' 不存在');
                return false;
            }
            if( $goodsTmpl['gtype']['props'] ){
                foreach( $goodsTmpl['gtype']['props'] as $propsk => $props ){
                    $this->ioSchema['csv']['props:'.$props['name']] = 'props/p_'.$propsk.'/value';
                    foreach( $props['options'] as $p => $v ){
                        $goodsTmpl['props_hash'][$props['name']][$v] = $p;
                    }
                }
            }

//            $oMlv = &$this->app->model('ome_lv');
//            foreach( $oMlv->getList('ome_lv_id,name','',0,-1) as $mlv ){
//                $this->ioSchema['csv']['price:'.$mlv['name']] = array('price/ome_lv_price/'.$mlv['ome_lv_id'].'/price','product');
//            }


            return array_flip($row);
        }else{
			 if(isset($this->good_nums)){
                        $this->good_nums ++;
                        if($this->good_nums > 5000){
                            $msg['error'] = "导入的商品数据量过大，请减少到5000单以下！";
                            return false;
                        }
                    }else{
                        $this->good_nums = 0;
                    }
            $mark = 'contents';
            if( !$row[$title['ibn:货号']] || in_array($row[$title['col:规格']],array('','-')) ){
                $newObjFlag = true;
            }
            if ($row[$title['col:重量']] < 0){
                $msg['error'] = "重量：".$row[$title['ibn:货号']]."重量必须大于等于0！";
                return false;
            }
            if ($this->bn_data)
            foreach ($this->bn_data as $v){
                if ($v[3] && $v[3] == $row[3]){
                   $this->same_bn[] = $row[3];
                   $this->flag = true;
                }
            }
            $this->bn_data[] = $row;
            return $row;
        }
        return null;
    }

    function ioSchema2sdf($data,$title,$csvSchema,$key = null){
        $rs = array();
        $subSdf = array();
        foreach( $csvSchema as $schema => $sdf ){
            $sdf = (array)$sdf;
            if( ( !$key && !$sdf[1] ) || ( $key && $sdf[1] == $key ) ){
                eval('$rs["'.implode('"]["',explode('/',$sdf[0])).'"] = $data[$title[$schema]];');
                unset($data[$title[$schema]]);
            /*}else if( ){
                eval('$rs["'.implode('"]["',explode('/',$sdf[0])).'"] = $data[$title[$schema]];');
                unset($data[$title[$schema]]);*/
            }else{
                $subSdf[$sdf[1]] = $sdf[1];
            }
        }
        if(!$key){
            foreach( $subSdf as $k ){
                foreach( $data[$k] as $v ){
                    $rs[$k][] = $this->ioSchema2sdf($v,$title,$csvSchema,$k);
                }
            }
        }
        foreach( $data as $orderk => $orderv ){
            if( substr($orderk,0,4 ) == 'col:' ){
                $rs[ltrim($orderk,'col:')] = $orderv;
            }
        }

        return $rs;

    }


     function prepared_import_csv_obj($data,$mark,$goodsTmpl,&$msg = ''){
        $gData = &$data['contents'];
        $gTitle = $data['title'];
        if (empty($gData) || !is_array($gData[0])) return null;
        $rs = array();
        //id

        $goodsId = $this->dump(array('bn|tequal'=>$gData[0][$gTitle['bn:商品编号']],'_bn_search'=>'tequal'),'goods_id');
        if( $goodsId['goods_id'] )
            $gData[0]['col:goods_id'] = $goodsId['goods_id'];
            $gData[0][$gTitle['col:上架']] = (in_array( $gData[0][$gTitle['col:上架']], array('Y','TRUE') )?'true':'false');

        foreach( $gTitle as $colk => $colv ){
            if( substr( $colk, 0,6 ) == 'props:' ){
                if( !$this->ioSchema['csv'][$colk] )
                    $msg['warning']['属性：'.ltrim($colk,'props:').'不存在'] = '属性：'.ltrim($colk,'props:').'不存在';
                else{
                    if( $gData[0][$gTitle[$colk]] && !array_key_exists( $gData[0][$gTitle[$colk]], $goodsTmpl['props_hash'][ltrim($colk,'props:')] ) )
                        $msg['warning']['属性值：'.$gData[0][$gTitle[$colk]].'不存在'] = '属性值：'.$gData[0][$gTitle[$colk]].'不存在';
                    $gData[0][$gTitle[$colk]] = $goodsTmpl['props_hash'][ltrim($colk,'props:')][$gData[0][$gTitle[$colk]]];
                }
            }
            if( (substr( $colk,0,6 ) == 'price:' || in_array( $colk , array('col:市场价','col:成本价','col:销售价') ) ) && $gData[0][$gTitle[$colk]] !== 0 && !$gData[0][$gTitle[$colk]] ){
                unset($gData[0][$gTitle[$colk]]);
            }
        }

        //分类
        /*$catPath = array();
        $oCat = &$this->app->model('goods_cat');
        $catId = 0;
        foreach( explode( '->',$gData[0][$gTitle['col:分类']] ) as $catName ){
            $aCatId = $oCat->dump(array('cat_name'=>$catName,'parent_id'=>$catId),'cat_id');
            if( $aCatId )
                $catId = $aCatId['cat_id'];
            else
                $catId = 0;
        }
        $catId = $oCat->dump($catId,'cat_id');
        if( !$catId['cat_id'] )
            $msg['warning']['分类：'.$gData[0][$gTitle['col:分类']].'不存在'] = '';
        $gData[0][$gTitle['col:分类']] = intval( $catId['cat_id']);*/

        //品牌
        $oBrand = &$this->app->model('brand');
        if( !$gData[0][$gTitle['col:品牌']] ){
            $brandId = array('brand_id'=>null);
        }else{
            $brandId = $oBrand->dump(array('brand_name'=>$gData[0][$gTitle['col:品牌']]),'brand_id');
            if( !$brandId['brand_id'] && $gData[0][$gTitle['col:品牌']] )
                $msg['warning']['品牌：'.$gData[0][$gTitle['col:品牌']].'不存在'] = '品牌：'.$gData[0][$gTitle['col:品牌']].'不存在';
        }
        $gData[0][$gTitle['col:品牌']] = trim($brandId['brand_id']?$brandId['brand_id']:null);

        //货品 处理return值
        $rs = $gData[0];
        $oPro = &$this->app->model('products');
        $spec = array();
        if( count( $gData ) == 1 ){
            unset($rs[$gTitle['col:规格']] );
            //$gData[0][$gTitle['ibn:货号']] = $gData[0][$gTitle['bn:商品编号']];

            //必填项判断
            if (!$gData[0][$gTitle['bn:商品编号']]){
                $msg = array( 'error'=>'商品编号不能为空！' );
                return false;
            }
            if (!$gData[0][$gTitle['ibn:货号']]){
                $msg = array( 'error'=>'货号不能为空！' );
                return false;
            }
            if ($gData[0][$gTitle['col:重量']] < 0){
                $msg = array( 'error'=>'重量必须大于等于0！' );
                return false;
            }

            $proId = $oPro->dump( array('bn'=>$gData[0][$gTitle['ibn:货号']],'_bn_search'=>'tequal'),'product_id,goods_id' );
            if( $proId['product_id'] ){
                $msg = array( 'error'=>'货号:'.$gData[0][$gTitle['ibn:货号']].' 已存在' );
                return false;
            }
            
            // 检查条形码重复
            if (trim($gData[0][$gTitle['barcode:条形码']]) != '') {
                $proId = $oPro->dump( array('barcode'=>$gData[0][$gTitle['barcode:条形码']],'_barcode_search'=>'tequal'),'product_id,goods_id' );
                if( $proId['product_id'] ){
                    $msg = array( 'error'=>'条形码:'.$gData[0][$gTitle['barcode:条形码']].' 已存在' );
                    return false;
                }
            }
            
			//判断只有主商品，没有规格货品的判断
			$goods_id = $oPro->dump( array('goods_id'=>$goodsId),'product_id' );
			if( $goods_id['product_id'] ){
                $msg = array( 'error'=>'商品编号:'.$gData[0][$gTitle['bn:商品编号']].' 已存在' );
                return false;
            }
            $rs['product'][0] = $gData[0];
            $rs['product'][0]['barcode'] = $gData[0][$gTitle['barcode:条形码']];
            if( $proId['product_id'] )
                $rs['product'][0]['col:product_id'] = $proId['product_id'];

        }else{
            reset($gData);
            $oSpec = &$this->app->model('specification');

            foreach( explode('|',$gData[0][$gTitle['col:规格']] ) as $speck => $specName ){
                $spec[$speck] = array(
                    'spec_name' => $specName,
                    'option' => array(),
                );
            }

            while( ( $aPro = next($gData) ) ){
                //必填项判断
                   if (!$aPro[$gTitle['bn:商品编号']]){
                    $msg = array( 'error'=>'商品编号不能为空！' );
                    return false;
                }
                if (!$aPro[$gTitle['ibn:货号']]){
                    $msg = array( 'error'=>'货号不能为空！' );
                    return false;
                }

                $aProk = key( $gData );
                
                // 检测条形码，不允许重复
                $proId = $oPro->dump( array('barcode'=>$aPro[$gTitle['barcode:条形码']],'_barcode_search'=>'tequal'),'product_id,goods_id' );
                if( $proId['product_id'] || ( !$rs['col:goods_id'] && $proId['product_id'] ) || ( $rs['col:goods_id'] && $rs['col:goods_id'] != $proId['goods_id'] ) ){
                    $msg = array( 'error'=>'条形码:'.$aPro[$gTitle['barcode:条形码']].' 已存在' );
                    return false;
                }
                
                $proId = $oPro->dump( array('bn'=>$aPro[$gTitle['ibn:货号']],'_bn_search'=>'tequal'),'product_id,goods_id' );

                if( $proId['product_id'] || ( !$rs['col:goods_id'] && $proId['product_id'] ) || ( $rs['col:goods_id'] && $rs['col:goods_id'] != $proId['goods_id'] ) ){
                    $msg = array( 'error'=>'货号:'.$aPro[$gTitle['ibn:货号']].' 已存在' );
                    return false;
                }
                $aPro['col:product_id'] = $proId['product_id'];
                $rs['product'][$aProk] = $aPro;

                foreach( explode('|',$aPro[$gTitle['col:规格']]) as $specvk => $specv ){
                    $spec[$specvk]['option'][$specv] = $specv;
                }
            }

            if ($spec)
            foreach($spec as $sk => $aSpec){
                $specIdList = $oSpec->getSpecIdByAll($aSpec);
                if ($specIdList)
                foreach( $specIdList as $sv ){
                    if( array_key_exists($sv['spec_id'],$goodsTmpl['gtype']['spec'] ) ){
                        $spec[$sk]['spec_id'] = $sv['spec_id'];
                    }
                }
                if( !$spec[$sk]['spec_id'] )
                    $spec[$sk]['spec_id'] = $specIdList[0]['spec_id'];
                if( !$spec[$sk]['spec_id'] ){
                    $msg = array('error'=>'规格：'.$aSpec['spec_name'].'出现错误 请检查');
                    return false;
                }
                $spec[$sk]['option'] = $oSpec->getSpecValuesByAll($spec[$sk]);
            }
            $pItem = 0;
            if ($rs['product'])
            foreach( $rs['product'] as $prok => $prov ){

                if( !($pItem++) )$rs['product'][$prok]['col:default'] = 1;
                $proSpec = explode('|',$prov[$gTitle['col:规格']]);
                $rs['product'][$prok]['col:spec_info'] = implode(',',$proSpec);
                $rs['product'][$prok]['col:barcode'] = $prov[$gTitle['barcode:条形码']];

                $rs['product'][$prok]['col:weight'] = $prov[$gTitle['col:重量']];
                $rs['product'][$prok]['col:unit'] = $prov[$gTitle['col:单位']];

                if ($proSpec)
                foreach( $proSpec as $aProSpeck => $aProSpec ){
                    $rs['product'][$prok]['col:spec_desc']['spec_value'][$spec[$aProSpeck]['spec_id']] = $spec[$aProSpeck]['option'][$aProSpec]['spec_value'];
                    $rs['product'][$prok]['col:spec_desc']['spec_private_value_id'][$spec[$aProSpeck]['spec_id']] = $spec[$aProSpeck]['option'][$aProSpec]['private_spec_value_id'];
                    $rs['product'][$prok]['col:spec_desc']['spec_value_id'][$spec[$aProSpeck]['spec_id']] = $spec[$aProSpeck]['option'][$aProSpec]['spec_value_id'];
                }
            }

            unset( $rs[$gTitle['col:规格']] );
            if ($spec)
            foreach( $spec as $sk => $sv ){
                foreach( $sv['option'] as $psk => $psv ){
                    $rs[$gTitle['col:规格']][$sv['spec_id']]['option'][$psv['private_spec_value_id']] = $psv;
                }
            }
       }


        $return =  $this->ioSchema2sdf( $rs,$gTitle, $this->ioSchema['csv'] );

        if ($return['product'])
        foreach( $return['product'] as $pk => $pv ){
            $return['product'][$pk]['name'] = $return['name'];
            if (!$return['product'][$pk]['weight'])
            $return['product'][$pk]['weight'] = $rs[$gTitle['col:重量']];
        }
        if (!$return['unit']) $return['unit'] = $return['product'][0]['unit'];

        $return['type']['type_id'] = intval( $goodsTmpl['gtype']['type_id'] );
		$this->g_data[] = $return;
        return $return;
    }

    function getProducts($gid, $pid=0){
        $sqlWhere = '';
        if($pid > 0) $sqlWhere = ' AND A.product_id = '.$pid;
        $sql = "SELECT A.*,B.image_default_id FROM sdb_ome_products AS A LEFT JOIN sdb_ome_goods AS B ON A.goods_id=B.goods_id WHERE A.goods_id=".intval($gid).$sqlWhere;
        return $this->db->select($sql);
    }
    function getGoodsIdByBn( $bn , $searchType = 'has') {

        switch($searchType){
            case'nohas':
                $goodsId = $this->db->select('SELECT g.goods_id FROM sdb_ome_goods g LEFT JOIN sdb_ome_products p ON g.goods_id = p.goods_id WHERE g.bn NOT LIKE "%'.$bn.'%" OR p.bn NOT LIKE "%'.$bn.'%"');
                break;
            case'tequal':
                $goodsId = $this->db->select('SELECT g.goods_id FROM sdb_ome_goods g LEFT JOIN sdb_ome_products p ON g.goods_id = p.goods_id WHERE g.bn in( "'.$bn.'") OR p.bn in( "'.$bn.'")');
                break;
            case'has':
            default:
                $goodsId = $this->db->select('SELECT g.goods_id FROM sdb_ome_goods g LEFT JOIN sdb_ome_products p ON g.goods_id = p.goods_id WHERE g.bn LIKE "%'.$bn.'%" OR p.bn LIKE "%'.$bn.'%"');
                break;
            case'head':
                $goodsId = $this->db->select('SELECT g.goods_id FROM sdb_ome_goods g LEFT JOIN sdb_ome_products p ON g.goods_id = p.goods_id WHERE g.bn LIKE "'.$bn.'%" OR p.bn LIKE "'.$bn.'%"');
                break;
            case'foot':
                $goodsId = $this->db->select('SELECT g.goods_id FROM sdb_shopex_goods g LEFT JOIN sdb_shopex_products p ON g.goods_id = p.goods_id WHERE g.bn LIKE "%'.$bn.'" OR p.bn LIKE "%'.$bn.'"');
                break;
        }

        $rs = array();
        if ($goodsId)
        foreach( $goodsId as $key=>$val) {
            if(!in_array($val['goods_id'],$rs)){
                $rs[] = $val['goods_id'];
            }
        }
        return $rs;
    }
    function getGoodsIdByBarcode($barcode){
        $goodsId = $this->db->select('SELECT g.goods_id FROM sdb_ome_goods g LEFT JOIN sdb_ome_products p ON g.goods_id = p.goods_id WHERE p.barcode LIKE "%'.addslashes($barcode).'%"');

        $rs = array();
        if ($goodsId)
        foreach( $goodsId as $key=>$val) {
            if(!in_array($val['goods_id'],$rs)){
                $rs[] = $val['goods_id'];
            }
        }
        return $rs;
    }
    function getMarketableById($gid){
        return $this->db->selectrow('SELECT marketable FROM sdb_ome_goods WHERE goods_id='.$gid);
    }
     function data2local( $data ){
        $title = array();
        if($data)
        foreach( $data as $aTitle ){
            $title[] = $this->charset->utf2local($aTitle);
        }
        return $title;
    }


    function searchOptions(){
        return array(
                'bn'=>app::get('base')->_('货号'),
                'barcode'=>app::get('base')->_('条形码'),
                'name'=>app::get('base')->_('商品名称'),
                'fuzzy_search'=>app::get('base')->_('模糊搜索'),
            );
    }


    function fgetlist_csv(&$data,$filter,$offset){
		@ini_set('memory_limit','64M');
        $subSdf = array(
            'product'=>array(
                '*',
                //array('price/ome_lv_price'=>array('*'))
            ),
            //'images'=>array('*',array(':image'=>array('*'))),
            //':brand'=>array('*')
            //':goods_type'=>array('*')
        );
        $limit = 40;
        if( $filter['_gType'] ){
            $title = array();
            if(!$data['title'])$data['title'] = array();
            $data['title'][''.$filter['_gType']] = '"'.implode('","',$this->io->data2local( $this->io_title(array('type_id'=>$filter['_gType']))) ).'"';

            return false;
        }
        $oGtype = &$this->app->model('goods_type');
        $bObj = &$this->app->model('brand');
        if(!$goodsList = $this->getList('goods_id',$filter,$offset*$limit,$limit))return false;
        foreach( $goodsList as $aFilter ){
            $aGoods = $this->dump( $aFilter['goods_id'],'*',$subSdf );
            $brand_detail = $bObj->dump(array('brand_id'=>$aGoods['brand']['brand_id']));
            $aGoods = array_merge($aGoods, array('brand'=>$brand_detail));
            if( !$aGoods )continue;
            if( !$this->csvExportGtype[$aGoods['type']['type_id']] ){
                $this->csvExportGtype[$aGoods['type']['type_id']] = $oGtype->dump($aGoods['type']['type_id'],'*');
                //$data['title'][$aGoods['type']['type_id']];
                $data['title'][$aGoods['type']['type_id']] = '"'.implode('","',$this->io->data2local($this->io_title($aGoods['type']))).'"';
            }

            $csvData = $this->sdf2Csv($aGoods);
            $data['content'][$aGoods['type']['type_id']] = array_merge((array)$data['content'][$aGoods['type']['type_id']],(array)$csvData);
        }

        $data['name'] = 'goods'.date('YmdHis');
        return true;

    }

    function export_csv($data){
        $output = array();
        foreach( $data['title'] as $k => $val ){
            $output[] = $val."\n".implode("\n",(array)$data['content'][$k]);
        }
        echo implode("\n",$output);
    }

    function sdf2csv( $sdfdata ){
        $rs = array();
//        $sdf = $this->_column();
//        $product = $sdfdata['product'];
        //        unset($sdfdata['product']);
        $conTmp = array();
        if ($this->io_title( $sdfdata['type'] ))
        foreach( $this->io_title( $sdfdata['type'] ) as $titleCol ){
            $conTmp[$titleCol] = '';
        }
        $gcontent = $conTmp;

        //$this->oSchema['csv'][$sdfdata['type']['type_id']]['col:市场价'] = 'mktprice';
        //$this->oSchema['csv'][$sdfdata['type']['type_id']]['col:成本价'] = 'cost';
        //$this->oSchema['csv'][$sdfdata['type']['type_id']]['col:销售价'] = 'price';
        $sdfdata['type']['name'] = $this->csvExportGtype[$sdfdata['type']['type_id']]['name'];
        if ($this->oSchema['csv'][$sdfdata['type']['type_id']])
        foreach( $this->oSchema['csv'][$sdfdata['type']['type_id']] as $title => $sdfpath ){
            if( !is_array($sdfpath) ){
                $tSdfCol = utils::apath($sdfdata,explode('/',$sdfpath));
                $gcontent[$title] = (is_array($tSdfCol)?$tSdfCol:$this->charset->utf2local($tSdfCol));
            }else{
                $gcontent[$title] = '';
            }
            if( substr($title,0,6) == 'props:' ){
                if( !$gcontent && $gcontent[$title]['value'] !== 0 ){
                    $gcontent[$title] = '';
                }else{
                    $k = explode('_',$sdfpath);
                    $k = $k[1];
                    if( $this->csvExportGtype[$sdfdata['type']['type_id']]['props'][$k]['options'] ){
                        $gcontent[$title] = $this->charset->utf2local( $this->csvExportGtype[$sdfdata['type']['type_id']]['props'][$k]['options'][$gcontent[$title]['value']] );
                    }else{
                        $gcontent[$title] = $this->charset->utf2local( $gcontent[$title]['value'] );
                    }
                }
            }
        }

        $cat = array();
        $oCat = &$this->app->model('goods_cat');
        $tcat = $oCat->dump($sdfdata['category']['cat_id'],'cat_path');
        if ($oCat->getList('cat_name'))
        foreach( $oCat->getList('cat_name') as $acat ){
            if( $acat ) $cat[] = iconv('UTF-8','GB2312',$acat['cat_name']);
        }
        //$gcontent['col:分类'] = implode('->',$cat);
        //$gcontent['col:上架'] = $gcontent['col:上架'] == 'true'?'Y':'N';

        //$this->oSchema['csv'][$sdfdata['type']['type_id']]['col:市场价'] = array('price/mktprice/price','product');
       // $this->oSchema['csv'][$sdfdata['type']['type_id']]['col:成本价'] = array('price/cost/price','product');
        //$this->oSchema['csv'][$sdfdata['type']['type_id']]['col:销售价'] = array('price/price/price','product');

        if( !$sdfdata['spec'] ){
            if ($sdfdata['product'])
            $product = current( $sdfdata['product'] );
//            $proContent = $conTmp;
            foreach( $this->oSchema['csv'][$sdfdata['type']['type_id']] as $title => $sdfpath ){
                if( is_array($sdfpath) && $sdfpath[1] == 'product' ){
                    $tSdfCol = $this->charset->utf2local(utils::apath($product,explode('/',(!is_array($sdfpath)?$sdfpath:$sdfpath[0]))));
                    $gcontent[$title] = $tSdfCol;
                }
            }
            $gcontent['col:规格'] = '-';
            $rs[0] = '"'.implode('","',$gcontent).'"';
        }else{

            $spec = array();
            if ($sdfdata['spec'])
            foreach( $sdfdata['spec'] as $aSpec ){
                $spec[] = $aSpec['spec_name'];
            }
            $gcontent['col:规格'] = $this->charset->utf2local( implode('|',$spec) );
            $oSpec = &$this->app->model('spec_values');

            $rs[0] = '"'.implode('","',$gcontent).'"';
            if ($sdfdata['product'])
            foreach( $sdfdata['product'] as $row => $aSdfdata ){
                $content = $gcontent;
                foreach( $this->oSchema['csv'][$sdfdata['type']['type_id']] as $title => $sdfpath ){
                    $content[$title] = $this->charset->utf2local(utils::apath($aSdfdata,explode('/',(!is_array($sdfpath)?$sdfpath:$sdfpath[0]))));
                }
                $specValue = array();
                foreach( $oSpec->getList('spec_value',array('spec_value_id'=>$aSdfdata['spec_desc']['spec_value_id']) ) as $aSpecValue ){
                    $specValue[] = $this->charset->utf2local($aSpecValue['spec_value']);
                }
                $content['col:规格'] = implode('|',$specValue);
                $content['bn:商品编号'] = $gcontent['bn:商品编号'];
                //$content['col:上架'] = $content['col:上架'] == 'true'?'Y':'N';
                $content['*:'.$sdfdata['type']['name']] = $this->charset->utf2local($sdfdata['type']['name']);
                $rs[$row] = '"'.implode('","',$content).'"';
            }

        }
        return $rs;
    }



    /*
     * 删除商品
     */
   function pre_recycle($data=null){
       $productObj = &$this->app->model('products');

       $orderItemObj = &$this->app->model('order_items');
       $pkgProductObj = &app::get('omepkg')->model('pkg_product');

       foreach ($data as $goods){
           if($goods['goods_id']){
               $products = $productObj->getList('product_id,store,store_freeze', array('goods_id'=>$goods['goods_id']), 0,-1);
               foreach ($products as $product){
                   $orders = $orderItemObj->getList('order_id', array('product_id'=>$product['product_id']), 0,-1);
                   $pkgProducts = $pkgProductObj->getList('goods_id', array('product_id'=>$product['product_id']), 0,-1);
                   if($orders || $pkgProducts || $product['store'] || $product['store_freeze']){
                       return false;
                   }
               }
           }
       }
       return true;
   }

   function pre_restore(&$data = null){
       $data['need_delete'] = true;
       if($data['product']){
           $bns = array();
           foreach($data['product'] as $p){
               $bns[] = $p['bn'];
           }

           $productObj = &$this->app->model('products');
           $exist_p = $productObj->getList('product_id',array('bn'=>$bns));
           if(is_array($exist_p) && count($exist_p)>0){
               return false;
           }
       }

       return true;
   }

   function checkIsUse(& $goods){
      $pids = array();
      foreach($goods['product'] as $product_id=>$p){
          $pids[] = $product_id;
          $p['is_use'] = 0;
          $goods['product'][$product_id] = $p;
      }
      $rows = $this->db->select('SELECT COUNT(item_id) AS _counts,product_id FROM sdb_ome_order_items WHERE product_id IN('.implode(',',$pids).') GROUP BY product_id ORDER BY product_id');
      foreach($rows as $row){
          if($row['_counts']>0){
              $goods['product'][$row['product_id']]['is_use'] = 1;
          }
      }
   }

   function finish_import_csv(){

	    $goodsdate = $this->g_data;
	    unset($this->g_data);
        $oQueue = &app::get('base')->model('queue');
		 $count = 0;
        $limit = 50;
        $page = 0;
		foreach($goodsdate as $goodSdf){
				if($count < $limit){
						$count ++;
					}else{
						$count = 0;
						$page ++;
					}
					 $goodsSdfs[$page][] = $goodSdf;
		}
		  foreach($goodsSdfs as $v){

            $queueData = array(
                'queue_title'=>'商品导入',
                'start_time'=>time(),
                'params'=>array(
                    'sdfdata'=>$v,
                    'app' => 'ome',
                    'mdl' => 'goods',
                ),
                'worker'=>'ome_goods_import.run',
            );
            $oQueue->save($queueData);

        }

		 app::get('base')->model('queue')->flush();
	}


}
